<template>
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        mode="default"
      />
      <Editor
        style="height: 500px; overflow-y: hidden;"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        mode="default"
        @onCreated="handleCreated"
        @onBlur="handleChange"
      />
    </div>
</template>

<script lang="ts" setup>
  import '@wangeditor/editor/dist/css/style.css' // 引入 css
  import { ElMessage } from 'element-plus'
  import { getFileHash } from '@/utils';
  import { onBeforeUnmount, ref, shallowRef, onMounted, toRef, defineEmits } from 'vue'
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  import { IEditorConfig, IToolbarConfig } from '@wangeditor/editor'
  import { getUploadUrl, saveFileUrl, uploadFile } from '@/api/file';

  const OSS = require("ali-oss");
  type AliOssOption = {
    dir: string;
    domain: string;
  }

  type InsertFnType = (url: string, alt: string, href: string) => void
  const editorRef = shallowRef()
  const editorConfig: Partial<IEditorConfig> = { MENU_CONF: {} }
  const props = defineProps({
    imgSaveType: String,
    content: {
      type: String,
      default: ""
    },
    changeContent: {
      type: Function
    },
    enableToolbar: {
      type: Array,
      default: []
    },
    disableToolbar: {
      type: Array,
      default: []
    }
  })
  const valueHtml = ref("")
  // Partial<IToolbarConfig>
  const toolbarConfig = ref(<Partial<IToolbarConfig>>{
    excludeKeys: props.disableToolbar
  })
// toolbar.getConfig().toolbarKeys

  // const result = await client.put('exampleobject.txt', path.normalize('D:\\localpath\\examplefile.txt')
  editorConfig.MENU_CONF!.uploadImage = {
    // 自定义上传
    async customUpload(file: File, insertFn: InsertFnType) {
            // console.log(file.stream())
      getFileHash(file).then((md5) =>{
        switch(props.imgSaveType){
          case 'alioss': 
            saveToAliOss(file, md5, insertFn)
            break;
          case 'local':
            saveToLocal(file, md5, insertFn)
        }
      })
    }
  }

  const saveToAliOss = (file: File, md5: string, insertFn: InsertFnType) => { 
    getUploadUrl(file.name, md5, file.type).then(({code, data, ext} : any)=>{
      if(code === 1){
        if(!data){
          insertFn(ext.url, 'alt', '')
          return
        }
        fetch(data, {
          method: "PUT",
          body: file,
          headers: {
            'Content-Type': file.type
          }
        }).then((res) => {
          console.log(res)
          insertFn(ext.url, 'alt', data)
          saveFileUrl(data, ext.id).then(res => {
            console.log(res)
          })
        })
      }
    })
  }
  const saveToLocal = (file: File, md5: string, insertFn: InsertFnType) => {
    uploadFile(file).then(({code, data, msg} : any) => {
      if(code){
        insertFn(data.url, 'alt', '')
      }else{
        ElMessage.error('Oops, 文件上传失败：'+msg)
      }
    })
  }
  // 模拟 ajax 异步获取内容
  onMounted(() => {
    // console.log(toolbarConfig.toolbarKeys)
    valueHtml.value = props.content
  })
  const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
    editor.setHtml(props.content)
    console.log(editor.getAllMenuKeys())
  }

  const handleChange = (editor: any) => {
    if (props.changeContent) {
      props.changeContent(editor.getHtml())
    }
  }

  // 组件销毁时，也及时销毁编辑器
  onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
  })
</script>